package com.example.new_trace_pda_check;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkhttpUtil {
    private OkHttpClient okHttpClient;
    private static OkhttpUtil myOkhttp = null;
    private Gson gson = new Gson();

    public OkhttpUtil() {
        init();
    }

    public Gson getGson() {
        return gson;
    }

    public static OkhttpUtil getInstance() {
        if (myOkhttp == null) {
            synchronized (OkhttpUtil.class) {
                if (myOkhttp == null) {
                    myOkhttp = new OkhttpUtil();
                }
            }
        }
        return myOkhttp;
    }

    public void init() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(500, TimeUnit.SECONDS).build();
    }

    /**
     * get异步请求
     *
     * @param url            请求地址
     * @param requestMessage 调用自定义内部接口
     */
    public void get(String url, final requestMessage requestMessage) {
        get(0, url, requestMessage);
    }


    public void get(int count, String url, final requestMessage requestMessage) {
        final Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestMessage.requestFail();
                e.printStackTrace();
               /* if (e instanceof SocketTimeoutException && count < 3) {
                    EventBus.getDefault().post(new DialogMessageEvent("超时重连第" + (count + 1) + "次尝试"));
                    get(count + 1, url, requestMessage);
                } else {
                    requestMessage.requestFail();
                }*/
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    Log.d("数据", response.body().string());
                }
            }
        });
    }


    /**
     * post异步请求
     *
     * @param url            请求地址
     * @param param          请求参数
     * @param requestMessage 调用内部自定义接口
     */
    public void post(String url, Map<String, String> param, final requestMessage requestMessage) {
        post(0, url, param, requestMessage);
    }

    public void post(int count, String url, Map<String, String> param, final requestMessage requestMessage) {
        FormBody.Builder body = new FormBody.Builder();
        if (param != null) {
            for (Map.Entry<String, String> data : param.entrySet()) {
                body.add(data.getKey(), data.getValue());
            }
        }
        Request request = new Request.Builder()
                .post(body.build())
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                requestMessage.requestFail();
               /* if (e instanceof SocketTimeoutException && count < 3) {
                    EventBus.getDefault().post(new DialogMessageEvent("超时重连第" + (count + 1) + "次尝试"));
                    post(count + 1, url, param, requestMessage);
                } else {
                    requestMessage.requestFail();
                }*/
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    Log.d("数据", response.body().string());
                }
            }
        });
    }

    public void postBitMap(String url, String status, List<File> fileList, final requestMessage requestMessage) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        if (!TextUtils.isEmpty(status)) {
            builder.addFormDataPart("status", status);
        }
        for (int i = 0; i < fileList.size(); i++) {
            builder.addFormDataPart("img" + i, "img" + "_" + i + ".jpg", RequestBody.create(MediaType.parse("image/jpg"), fileList.get(i)));
        }

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                requestMessage.requestFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    Log.d("数据", response.body().string());
                }
            }
        });
    }

    //系统时间获取方法
    public String getDate() {
        //获取系统的日期时间
        Calendar calendar = Calendar.getInstance();
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(calendar.getTime());
    }

    /**
     * 自定义请求失败与成功接口
     */
    public interface requestMessage {

        void requestFail();

        void requestSuccess(Response response) throws IOException;
    }
}
